import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["slide", "pagination", "next", "prev"]
  
  connect() {
    this.currentIndex = 0
    this.slides = this.slideTargets
    this.totalSlides = this.slides.length
    this.isAnimating = false
    
    // Initialize pagination
    this.initializePagination()
    
    // Show first slide
    this.showSlide(0)
    
    // Start autoplay
    this.startAutoplay()
    
    // Add event listeners for navigation
    if (this.hasNextTarget) {
      this.nextTarget.addEventListener('click', () => this.nextSlide())
    }
    if (this.hasPrevTarget) {
      this.prevTarget.addEventListener('click', () => this.prevSlide())
    }
  }

  disconnect() {
    this.stopAutoplay()
    if (this.hasNextTarget) {
      this.nextTarget.removeEventListener('click', () => this.nextSlide())
    }
    if (this.hasPrevTarget) {
      this.prevTarget.removeEventListener('click', () => this.prevSlide())
    }
  }

  initializePagination() {
    if (!this.hasPaginationTarget) return
    
    this.paginationTarget.innerHTML = ''
    this.slides.forEach((_, index) => {
      const dot = document.createElement('span')
      dot.classList.add('pagination-dot')
      dot.dataset.index = index
      dot.addEventListener('click', () => this.goToSlide(index))
      this.paginationTarget.appendChild(dot)
    })
  }

  showSlide(index) {
    if (this.isAnimating) return
    this.isAnimating = true
    
    // Hide all slides
    this.slides.forEach(slide => {
      slide.style.display = 'none'
      slide.classList.remove('active')
    })
    
    // Show current slide
    this.slides[index].style.display = 'block'
    this.slides[index].classList.add('active')
    
    // Update pagination
    this.updatePagination(index)
    
    this.currentIndex = index
    this.isAnimating = false
  }

  updatePagination(index) {
    if (!this.hasPaginationTarget) return
    
    const dots = this.paginationTarget.querySelectorAll('.pagination-dot')
    dots.forEach(dot => dot.classList.remove('active'))
    dots[index].classList.add('active')
  }

  nextSlide() {
    const nextIndex = (this.currentIndex + 1) % this.totalSlides
    this.showSlide(nextIndex)
  }

  prevSlide() {
    const prevIndex = (this.currentIndex - 1 + this.totalSlides) % this.totalSlides
    this.showSlide(prevIndex)
  }

  goToSlide(index) {
    this.showSlide(index)
  }

  startAutoplay() {
    this.autoplayInterval = setInterval(() => {
      this.nextSlide()
    }, 5000)
  }

  stopAutoplay() {
    if (this.autoplayInterval) {
      clearInterval(this.autoplayInterval)
    }
  }
} 